#-*-coding:utf-8-*-
from app.send_email import sent_email
from app.send_sms import send_sms
from app.db_models import *
from app.query_elec import query_elec_fun
import threading
import time
from sqlalchemy.orm import sessionmaker


def query():
    """遍历数据库，找出电量不足的宿舍"""
    li = []  # 用于存放电量不足的寝室
    Session = sessionmaker()  # 创建session
    Session.configure(bind=db.engine)
    sess = Session()
    # 返回一个不重复的列表，列表的每一个元素是特殊的元组
    all_dom = sess.query(Elec_Users.room_num).distinct()
    sess.close()  # 关闭session
    for i in all_dom:  # 查询每一个宿舍
        each_dom_num = i[0]
        to_query = query_elec_fun(each_dom_num)
        if to_query == "NoFound":
            continue
        elif to_query == "Timeout!":
            continue
        else:
            remaining_time = to_query.get('remaining_time')
            if remaining_time == ">10":
                continue
            else:
                if int(remaining_time) <= 2:  # 找到预计剩余时间小于等于两天的宿舍
                    dic = {"room_num": each_dom_num,
                           "new_reading": to_query['new_reading']}
                    li.append(dic)
    return li


def send():
    """将电量不足的宿舍与上次通知的宿舍比对，不重合的将发送通知"""
    print "task start!"
    start = time.time()  # 任务开始时间
    need_to_info_dom = query()  # 经查询需要通知的所有宿舍
    li = []  # 存放需要通知的宿舍
    for check in need_to_info_dom:  # 遍历本次查询出电量不足的宿舍
        last_info_dom = Elec_Informed.query.filter_by(
            room_num=check["room_num"]).first()  # 检查表中是否存在该宿舍
        if last_info_dom:
            if check["new_reading"] == last_info_dom.new_reading:  # 如果最新读数和原来的相同，则忽略本宿舍
                continue
            else:  # 如果最新读数与原来的不同，则更新记录并添加进通知列表li
                last_info_dom.new_reading = check["new_reading"]
                db.session.commit()
                li.append(check.get("room_num"))
        else:  # 若不存在该宿舍，则添加到数据表及li中
            NewUser = Elec_Informed(room_num=check["room_num"],
                                    new_reading=check["new_reading"])
            db.session.add(NewUser)
            db.session.commit()
            li.append(check["room_num"])

    if len(li) > 0:
        sms_users = ""  # 用于存储需要短信通知的用户
        email_users = []  # 用于存储需要邮件通知的用户
        for num in li:
            Session = sessionmaker()  # 创建session
            Session.configure(bind=db.engine)
            sess = Session()
            users = sess.query(Elec_Users).filter_by(room_num=num).all()
            sess.close()  # 关闭session
            for i in users:
                if i.contact_way == "sms":
                    sms_users = (i.contact_info + ';' + sms_users)
                elif i.contact_way == "":
                    continue
                else:
                    email_users.append(i.contact_info)
        if len(sms_users) > 0:
            print "The sms users:", sms_users
            # send_sms(sms_users)
        if len(email_users) > 0:
            print "The email users:", email_users
            # sent_email(email_users)
    print "The dom which need to informed:", li

    end = time.time()  # 任务结束时间
    used_time = end - start
    current = time.asctime(time.localtime(end))  # 获取格式化的时间
    Session = sessionmaker()  # 创建session
    Session.configure(bind=db.engine)
    sess = Session()
    count = sess.query(Elec_Users).count()  # 查询用户总数
    sms_info = sess.query(Elec_Users).filter_by(
        contact_way='sms').count()  # 查询使用短信通知的用户总数
    email_info = sess.query(Elec_Users).filter_by(
        contact_way='email').count()  # 查询使用邮箱通知的用户总数
    sess.close()  # 关闭session
    print "This task used: %s second" % used_time
    print "Current time:", current
    print "The sum of all users is:", count
    print "The sum of users who used sms is:", sms_info
    print "The sum of users who used email is:", email_info
    set_timer()


def set_timer():
    t = threading.Timer(7200, send)  # 每隔12小时(43200s)遍历一遍数据库并发送通知消息
    t.start()

if __name__ == '__main__':
    send()
